package com.dc.coroutine

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

class FlowViewModel : ViewModel() {

    val stateFlow = MutableStateFlow("")

    val sharedFlow = MutableSharedFlow<String>()

    fun requestData(count: Int) {
        viewModelScope.launch {
            flow {
                delay(2000)
                emit("网络请求$count")
            }.flowOn(Dispatchers.IO).catch { }.collect {
                stateFlow.value = it
                sharedFlow.emit(it)
            }
        }
    }
}